import { ref, reactive } from 'vue'
import app from '@/app'
import math from '@/app/math'

import { latest, post } from '@/api/erp/bills'
import { sum } from '@/api/erp/cash'
import { totalGroup } from '@/api/store/order_pay'

import accountModel from '@/model/account'
import checkoutModel from '@/model/account/checkout'
import printerModel from '@/model/printer'
import payModel from '@/plugin/config/model/pay'
import model from '../model'

// 统计钱箱
export default {
  // 查询条件
  where: reactive({
    checkout_id: accountModel.getCheckout().id,
    time: [0, 0]
  }),

  // 支付统计
  total: ref({ money: 0 }),

  // 数据统计
  data: reactive({
    start_money: 0,
    cash_money: 0,
    pay_money: 0,
    with_money: 0,
    sub_money: 0,
    total: 0
  }),

  // 钱箱统计
  async get() {
    // 对帐初始资金
    await this.startMoney()

    // 统计流水
    await this.cashMoney()

    // 统计支付
    await this.payMoney()
    
    // 统计余额
    this.totalMoney()
  },

  // 统计对帐初始资金
  async startMoney() {
    // 拉取最后一次对帐
    const bills = await latest(this.where)

    // 时间条件修改为最后一次对帐时间
    this.where.time = [
      // 为了避免与上次对帐时间有重合，要 + 1
      bills.end_time ? Number(bills.end_time) + 1 : 0, 
      app.time.unix(app.time.current())
    ]

    // 上次对帐最终金额为本次初始金额
    this.data.start_money = bills.total ?? 0
  },

  // 流水统计
  async cashMoney() {
    // 拉取流水统计
    const cash = await sum({ bills: false, ...this.where })
    this.data.cash_money = cash.sum ?? 0
  },

  // 支付统计
  async payMoney() {
    let money = 0
    const total = { money: 0 };

    // 拉取支付统计
    (await totalGroup(this.where)).forEach(item => {
      // 默认支付方式加入统计
      if(payModel.getDefault().id == item.pay_id) {
        money = math.add(money, item.money)
      }
      // 支付方式统计
      total[item.pay_id] = item.money
      total.money = math.add(total.money, item.money)
    })

    this.total.value = total
    this.data.pay_money = money
  },

  // 统计钱箱余额
  totalMoney() {
    this.data.total = math.add(
      this.data.start_money,
      math.add(this.data.cash_money, this.data.pay_money)
    )

    this.data.total = math.sub(this.data.total, this.data.with_money)

    // 差额
    this.data.sub_money = math.sub(this.data.with_money, this.data.pay_money)
  },

  // 提交统计数据
  async post(form) {
    // 整理数据
    const data = { 
      ...form, 
      ...this.data,
      start_time: this.where.time[0],
      end_time: this.where.time[1],
    }
    
    return new Promise((resolve, jeject) => {
      // 判断时间区间
      if(this.where.time[1] - this.where.time[0] < 100) {
        app.ui.message('warning', 'time', 'Cash.bills')
        return jeject()
      }

      this.print(data)
      
      post(data).then(res => {
        // 产生提现流水
        if(this.data.with_money != 0) {
          model.post({ money: -1 * this.data.with_money, bills_id: res.data.id })
          this.data.with_money = 0
        }
        // 重新统计
        this.get()
        app.ui.message('success', res.message)
        resolve(res)
      }).catch(res => {
        app.ui.message('error', 'error.' + res.message)
        jeject(res)
      })
    })
  },

  // 打印
  print(data) {
    const checkout = checkoutModel.find(this.where.checkout_id)
    const account = accountModel.getData()
    const time = this.where.time
    console.log(account)
    const print = [{
        "a": "AlignCenter" 
      }, {
        "a": "Size",
        "p": [1]
      }, {
        "a": "Text",
        "p": [checkout.name]
      }, {
        "a": "Size",
        "p": [0]
      }, {
        "a": "Line"
      }, {
        "a": "Text",
        "p": ["Fecha: " + app.time.format(time[0]) +  ' - ' + app.time.format(time[1])]
      }, {
        "a": "AlignLeft" 
      }, {
        "a": "Line"
      }, {
        "a": "Bold"
      }, {
        "a": "Text",
        "p": ["ESTADO"]
      }, {
        "a": "BoldOff"
      }, {
        "a": "Separator",
        "p": ["-"]
      }, {
        "a": "Table",
        "p": [['Total', app.money(this.total.value.money, false)], [26, -22]]
      }
    ]
    
    payModel.getAll().forEach((item) => {
      print.push({
        "a": "Table",
        "p": [[item.name, app.money(this.total.value[item.id], false)], [26, -22]]
      })
    })

    payModel.getAll().forEach((item, index) => {
      // 判断是否为第一支付
      if(index == 0) {
        print.push({
          "a": "Line"
        }, {
          "a": "Bold"
        }, {
          "a": "Text",
          "p": ["ESTADO DE LA CAJA (" + item.name + ")"]
        }, {
          "a": "BoldOff"
        }, {
          "a": "Separator",
          "p": ["-"]
        }, {
          "a": "Table",
          "p": [['Saldo inicial', app.money(data.start_money, false)], [26, -22]]
        }, {
          "a": "Table",
          "p": [['Ingreso', app.money(this.total.value[item.id], false)], [26, -22]]
        }, {
          "a": "Table",
          "p": [['Movimiento de caja', app.money(data.cash_money, false)], [26, -22]]
        }, {
          "a": "Table",
          "p": [['Retirado por [' + account.name + ']', app.money(data.with_money, false)], [26, -22]]
        }, {
          "a": "Table",
          "p": [['Saldo final', app.money(data.total, false)], [26, -22]]
        }, {
          "a": "Table",
          "p": [['Descuadre', app.money(data.sub_money, false)], [26, -22]]
        }, {
          "a": "Line"
        })
      } else if(index == 1) {
        print.push({
          "a": "Line"
        }, {
          "a": "Bold"
        }, {
          "a": "Text",
          "p": ["ESTADO DEL BANCO (" + item.name + ")"]
        }, {
          "a": "BoldOff"
        }, {
          "a": "Separator",
          "p": ["-"]
        }, {
          "a": "Table",
          "p": [['Ingreso', app.money(this.total.value[item.id], false)], [26, -22]]
        }, {
          "a": "Line"
        })
      }
    })

    printerModel.printSmall(print)
  }
}